package com.biz.utils.okhttp;

import okhttp3.OkHttpClient.Builder;

import javax.net.ssl.*;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

/**
 * @Package: com.biz.utils.http <br>
 * @Author: yangfan <br>
 * @Date: 2021/01/09 14:42 <br>
 * @Version: V1.0
 */
public class OKHttpClientBuilder {

    public OKHttpClientBuilder() {
    }

    public static Builder buildOKHttpClient() {
        try {
            TrustManager[] trustAllCerts = buildTrustManagers();
            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init((KeyManager[])null, trustAllCerts, new SecureRandom());
            SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
            Builder builder = new Builder();
            builder.sslSocketFactory(sslSocketFactory);
            builder.hostnameVerifier((hostname, session) -> {
                return true;
            });
            return builder;
        } catch (KeyManagementException | NoSuchAlgorithmException var4) {
            var4.printStackTrace();
            return new Builder();
        }
    }

    private static TrustManager[] buildTrustManagers() {
        return new TrustManager[]{new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {

            }

            @Override
            public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {

            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }
        }};
    }
}
